#include "include/muduo/net/TcpClient.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/net/TcpConnection.h"
#include "include/muduo/base/CountDownLatch.h"
#include <iostream>
#include <functional>


class TranslateClient
{
public:
    TranslateClient(const std::string& sip,int sport)
    :_latch(1),
    _client(_loopthread.startLoop(),muduo::net::InetAddress(sip,sport),"TranslateClient")
    {
        _client.setConnectionCallback(std::bind(&TranslateClient::onConnection, this,
                                                std::placeholders::_1)); // placeholders是预留参数位
        _client.setMessageCallback(std::bind(&TranslateClient::onMessage, this,
                                             std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    //连接服务器，需要阻塞等待连接建立之后再返回
    void connect()
    {
        _client.connect();
        _latch.wait();
    }

    
    bool send(const std::string& msg)
    {
        //连接状态正常再发送
        if(_conn->connected())
        {
            _conn->send(msg);
            return true;
        }
        return false;
    }

private:
    // 新连接建立成功时的回调函数，需要唤醒上边的阻塞
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        // 新连接建立成功时的回调函数
        if(conn->connected())
        {
            //唤醒主线程的阻塞
            _latch.countDown();
            _conn=conn;
        }
        else
        {
            _conn.reset();  
        }
    }

     // 通信连接收到请求时的回调函数
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        std::cout<<"翻译结果:"<<buf->retrieveAllAsString()<<std::endl;
    }

private:
    muduo::CountDownLatch _latch;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
};


int main()
{
    TranslateClient client("1.12.222.191",8005);
    // TranslateClient client("127.0.0.1",8005);
    client.connect();

    while(1)
    {
        std::string buf;
        std::cin>>buf;
        client.send(buf);
    }

    return 0;
}